use crate::models;
use models::ProxyConfig;
use std::fs::File;
use std::io::copy;

use reqwest::{header, Client, Proxy};

pub async fn download_image(url: &str, path: &str, proxy_str: &str) {
    let proxy: ProxyConfig = serde_json::from_str(proxy_str).expect("proxy config error");

    let user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";
    let client = Client::builder()
        .proxy(
            Proxy::https(format!("{}:{}", proxy.url, proxy.port))
                .unwrap()
                .basic_auth(&proxy.username, &proxy.password),
        )
        .timeout(std::time::Duration::from_secs(100)) // 设置超时时间
        .default_headers({
            let mut headers = header::HeaderMap::new();
            headers.insert(
                header::USER_AGENT,
                header::HeaderValue::from_str(user_agent).unwrap(),
            );
            headers
        })
        .build()
        .unwrap();

    // 发送请求并处理可能的错误
    let response = match client.get(url).send().await {
        Ok(value) => value,
        Err(e) => {
            println!("{:?}", e);
            return ;
        }
    };
    println!("请求状态码：{}", response.status());

    if response.status().is_success() {
        let bytes = response.bytes().await.unwrap();
        let mut file = File::create(path).unwrap();
        copy(&mut bytes.as_ref(), &mut file).unwrap();
        println!("图片下载成功，已保持为 {}", path);
    } else {
        println!("请求失败，状态码：{}", response.status());
    }
}
